from django.views.decorators.csrf import csrf_exempt
from app.dish_recognition.models import IMG
from app.dish_recognition import dish_reco
from django.http import JsonResponse
from django.http import HttpResponse
from .resources import IMGResource


@csrf_exempt
def img_recognition(request):
    if request.method == "POST":
        img = request.FILES.get('file')
        name = request.FILES.get('file').name
        access_token = request.POST.get("access_token")
        IMG.objects.create(img=img,name=name)
        try:
            #调用图像识别
            result = dish_reco.img_reco(name, access_token)
            data={
                "errcode":0,
                "errmsg": "成功",
                "data":{
                    "content":result
                }
            }
        except:
            data = {
                "errcode": 10000,
                "errmsg": "失败"
            }

    return JsonResponse(data=data)


#导出图片
def exportImg(request):
    img_resoure = IMGResource()
    dataset = img_resoure.export()
    response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="img.xls"'
    return response